package com.lb.shopguide.ui.fragment.guide.miji;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterMijiList;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.MijiBean;
import com.lb.shopguide.entity.TutorTypeBean;
import com.lb.shopguide.event.guide.MijiLikeEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by kang on 2017/6/7.
 */

public class FragmentMijiList extends BaseMainFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterMijiList mAdapterMijiList;

    private List<MijiBean> mMijiBeanList;
    private TutorTypeBean tutorTypeBean;

    private MijiBean curMiji;
    private int curPos;
    private boolean liked;

    public static FragmentMijiList newInstance(TutorTypeBean typeBean) {
        FragmentMijiList fragmentMijiList = new FragmentMijiList();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.TUTOR_TYPE_BEAN, typeBean);
        fragmentMijiList.setArguments(bundle);
        return fragmentMijiList;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_miji_list;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mMijiBeanList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.TUTOR_TYPE_BEAN)) {
            tutorTypeBean = (TutorTypeBean) bundle.getSerializable(AppConstant.TUTOR_TYPE_BEAN);
            sendRequestGetMijiList();
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {


        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty;
        tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有该类秘籍");

        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterMijiList = new AdapterMijiList(R.layout.item_miji_list, mMijiBeanList);
        mRecyclerView.setAdapter(mAdapterMijiList);
        mAdapterMijiList.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                curPos = position;
                MijiBean mijiBean = mMijiBeanList.get(position);
                String url;
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    url = "https://singlepage.storeer.com/v2/esotericaInfo?esoCode=" + mijiBean.getEsoCode() + "&token=" + mUserConfigManager.getUserToken();
                } else {
                    url = "http://192.168.1.102:8088/v2/esotericaInfo?esoCode=" + mijiBean.getEsoCode() + "&token=" + mUserConfigManager.getUserToken();
                }
                EventBus.getDefault().post(new StartBrotherEvent(FragmentMijiDetail.newInstance(url, mijiBean.getEsoCode(), mijiBean.getEsoTitle())));
            }
        });
        mAdapterMijiList.setOnLikeClickListener(new AdapterMijiList.OnLikeClickListener() {
            @Override
            public void onLikeClick(int pos, boolean checked) {
                curPos = pos;
                liked = checked;
                curMiji = mMijiBeanList.get(pos);
                sendRequestPraiseMiji(curMiji.getEsoCode());
            }

        });
        if (tutorTypeBean.getTutorCode() != null) {
            addHeaderView();
        }
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterMijiList.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentMijiList.class.getName();
    }

    private void addHeaderView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_miji_header, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvTutorName = view.findViewById(R.id.tv_tutor_name);
        TextView tvPosition = view.findViewById(R.id.tv_position);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        ImageView ivTutorAvatar = view.findViewById(R.id.iv_tutor_avatar);

        ImageLoaderUtils.display(mContext, ivTutorAvatar, tutorTypeBean.getTutorPicUrl());
        tvPosition.setText(tutorTypeBean.getTutorTitle());
        tvTutorName.setText(tutorTypeBean.getTutorName());
        tvDesc.setText(tutorTypeBean.getTutorShortDesc());
        mAdapterMijiList.addHeaderView(view);
    }

    private void sendRequestGetMijiList() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObjMiji = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    JSONArray jsonMiji;
                    try {
                        jsonMiji = jsonObjMiji.getJSONArray("esoList");
                        if (jsonMiji.length() != 0) {
                            for (int i = 0; i < jsonMiji.length(); i++) {
                                MijiBean bean = JsonUtil.getGson().fromJson(jsonMiji.getString(i), MijiBean.class);
                                bean.setShortDesc(tutorTypeBean.getTutorShortDesc());
                                mMijiBeanList.add(bean);
                            }
                            mAdapterMijiList.setNewData(mMijiBeanList);
                        } else {
                            bindEmpty();
                        }
                        finishRefresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodGuide.getMijiListByTutorCode(new SimpleLbObserver(listener, otherListener), tutorTypeBean.getTutorCode(), mUserConfigManager.getUserId(), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestPraiseMiji(String mijiCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    curMiji.setLiked(liked);
                    if (liked) {
                        curMiji.setEsoLikedNum(curMiji.getEsoLikedNum() + 1);
                        ToastUtils.showShort("点赞成功");
                    } else {
                        curMiji.setEsoLikedNum(curMiji.getEsoLikedNum() - 1);
                        ToastUtils.showShort("取消点赞成功");
                    }
                    mAdapterMijiList.setData(curPos, curMiji);
                }
            }
        };
        ApiMethodGuide.praiseMiji(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), mijiCode, this, FragmentEvent.DESTROY_VIEW);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMijiLike(MijiLikeEvent event) {
        MijiBean miji = event.getMijiBean();
        MijiBean mijiBean = mMijiBeanList.get(curPos);
        mijiBean.setLiked(miji.isLiked());
        mijiBean.setEsoLikedNum(miji.getEsoLikedNum());
        mAdapterMijiList.setData(curPos, mijiBean);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void bindEmpty() {
        if (tutorTypeBean.getTutorCode() == null) {
            mMijiBeanList.clear();
            mAdapterMijiList.setNewData(mMijiBeanList);

            mNoData = true;
            onRefresh();
        }
    }

    @Override
    public void onRefresh() {
        mAdapterMijiList.setEnableLoadMore(false);
        if (mError) {
            mAdapterMijiList.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterMijiList.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    public void refresh() {
        mMijiBeanList = new ArrayList<>();
        sendRequestGetMijiList();
    }

    @Override
    public void onLoadMoreRequested() {

    }
}
